<template>
  <div style="">
    新增资讯
    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item label="资讯标题">
        <el-input v-model="form.title"></el-input>
      </el-form-item>
      <el-form-item label="简讯">
        <el-input v-model="form.shortcontent" maxlength="20"></el-input>
      </el-form-item>
      <el-form-item label="资讯图片">
        <el-upload
            class="avatar-uploader"
            action="https://maisheng-lunbo-1305747968.cos.ap-nanjing.myqcloud.com"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="befup"
        >
          <img v-if="form.thumb_url" :src="form.thumb_url" class="avatar"/>
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="资讯时间">
        <el-date-picker v-model="form.time" type="date" placeholder="选择日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="资讯内容">
        <vue-ueditor-wrap v-model="form.content" :config="editorConfig"></vue-ueditor-wrap>
      </el-form-item>
      <el-button type="success" style="display:block;width: 200px;margin-left: auto;margin-right: auto" @click="tijiao">
        提交
      </el-button>
    </el-form>
  </div>
</template>

<script>

import {ElMessage} from 'element-plus'

export default {
  name: "AddZixun",
  props: ["jwttoken"],
  data() {
    return {
      form: {
        title: '',
        thumb_url: '',
        time: '',
        content: '',
        cos: {},
      }
    }
  },
  created() {
    // 更多 UEditor 配置，参考 http://fex.baidu.com/ueditor/#start-config
    this.editorConfig = {
      // 访问 UEditor 静态资源的根路径，可参考 https://hc199421.gitee.io/vue-ueditor-wrap/#/faq
      UEDITOR_HOME_URL: '/UEditor/',
      // 服务端接口（这个地址是我为了方便各位体验文件上传功能搭建的临时接口，请勿在生产环境使用！！！）
      // serverUrl: '//ueditor.szcloudplus.com/cos',
      initialFrameWidth: 1000  //初始化编辑器宽度,默认1000
      , initialFrameHeight: 500  //初始化编辑器高度,默认320
    };
    this.gettmpcos();
  },
  methods: {
    gettmpcos: function () {
      console.log("cos");
      let that = this;
      var cos = new this.$COS({
        getAuthorization: function (options, callback) {
          console.log(options);
          console.log(callback);
          // 异步获取临时密钥
          //   $.get(
          //     "http://example.com/server/sts.php",
          //     {
          //       bucket: options.Bucket,
          //       region: options.Region,
          //     },
          //     function (data) {
          //       var credentials = data && data.credentials;
          //       if (!data || !credentials)
          //         return console.error("credentials invalid");

          //     }
          //   );

          that.$jquery.ajax({
            async: false,
            type: "GET",
            dataType: "json",
            url: that.$baseurl + "createCosTmplunbo",
            beforeSend: function (request) {
              request.setRequestHeader("Authorization", that.jwttoken);
            },
            success: function (rtn) {
              if (rtn.code == -5) {
                that.$emit("loginstate1", -1);
              }
              if (rtn.code == 1) {
                var credentials = rtn.data && rtn.data.credentials;
                if (!rtn.data || !credentials)
                  return console.error("credentials invalid");
                callback({
                  TmpSecretId: credentials.tmpSecretId,
                  TmpSecretKey: credentials.tmpSecretKey,
                  SecurityToken: credentials.sessionToken,
                  // 建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
                  StartTime: rtn.data.startTime, // 时间戳，单位秒，如：1580000000
                  ExpiredTime: rtn.data.expiredTime, // 时间戳，单位秒，如：1580000900
                });
              }
            },
          });
        },
      });
      console.log(cos);
      this.cos = cos;
    },
    befup: function (file) {
      // this.temp(file)
      // console.log(filelist);

      let that = this;
      let key = that.randomString();
      this.cos.putObject(
          {
            Bucket: "maisheng-lunbo-1305747968" /* 必须 */,
            Region: "ap-nanjing" /* 存储桶所在地域，必须字段 */,
            Key: key + ".png" /* 必须 */,
            StorageClass: "STANDARD",
            Body: file, // 上传文件对象
            onProgress: function (progressData) {
              that.pshow = true;
              console.log(progressData.percent);
              that.percentage = progressData.percent.toFixed(2) * 100;
            },
          },
          function (err, data) {
            console.log(err || data);
            if (err) {
              that.$notify.error({
                title: "错误",
                message: "上传失败",
              });
            } else {
              that.$notify({
                title: "成功",
                message: "上传成功",
                type: "success",
              });
              that.form.thumb_url = 'https://' + data.Location
              // that.uploadsql()
              // setTimeout(function () {
              //   location.reload()
              // }, 2000)
            }
          }
      );
    },
    randomString: function () {
      let e = 32;
      let t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
      let a = t.length;
      let n = "";
      for (let i = 0; i < e; i++) n += t.charAt(Math.floor(Math.random() * a));
      return n;
    },
    tijiao: function () {
      let that = this
      if (!this.form.title) {
        ElMessage.warning({
          message: '标题不能为空',
          type: 'warning',
        })
        return false;
      }
      if (!this.form.thumb_url) {
        ElMessage.warning({
          message: '图片必须上传',
          type: 'warning',
        })
        return false;
      }
      if (!this.form.time) {
        ElMessage.warning({
          message: '时间必须选择',
          type: 'warning',
        })
        return false;
      }
      if (!this.form.shortcontent) {
        ElMessage.warning({
          message: '简讯不能为空',
          type: 'warning',
        })
        return false;
      }
      if (!this.form.content) {
        ElMessage.warning({
          message: '内容不能为空',
          type: 'warning',
        })
        return false;
      }
      // return false;
      let ltime = that.form.time
      let lmonth = parseInt(ltime.getMonth()) + 1
      let ntime = ltime.getUTCFullYear() + '-' + lmonth + '-' + ltime.getDate()
      this.$jquery.ajax({
        async: false,
        type: "post",
        dataType: "json",
        url: that.$baseurl + "addZixun",
        beforeSend: function (request) {
          request.setRequestHeader("Authorization", that.jwttoken);
        },
        data: {
          title: that.form.title,
          thumb_url: that.form.thumb_url,
          content: that.form.content,
          time: ntime,
          shortcontent: that.form.shortcontent

        },
        success: function (rtn) {
          if (rtn.code == -5) {
            that.$emit("loginstate1", -1);
          }
          if (rtn.code == 1) {
            ElMessage.success({
              message: '添加成功',
              type: 'success',
            })
          } else {
            ElMessage.error('添加失败')
          }

        },
      });
    }
  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 240px;
  height: 178px;
  display: block;
}

.avatar-uploader {
  width: 240px;
  height: 178px;
  border: 1px dashed grey;
}


/deep/ .el-form-item__content {
  margin-left: 0px;
  margin-right: auto;
  width: 178px;
}

/deep/ .el-input__inner {
  width: 800px;
}
</style>
